<script>
import utils from "./common/utils.js";
import config from "./env/config.js";
export default {
  onLaunch: function (e) {
    // #ifdef H5
    this.$router.afterEach((to, from) => {
      const u = navigator.userAgent.toLowerCase();
      if (
        u.indexOf("like mac os x") < 0 ||
        u.match(/MicroMessenger/i) != "micromessenger"
      )
        return;
      if (to.path !== location.pathname) {
        location.assign(config.h5_addr + to.fullPath);
      }
    });
    // #endif
    // #ifdef APP-PLUS
    this.isFirstEnter();
    // #endif
    console.log("App Launch");
    //#ifdef MP-WEIXIN
    //检查更新
    this.updateManager();
    //#endif
    let self = this;
    // #ifdef APP-PLUS
    plus.runtime.getProperty(plus.runtime.appid, function (widgetInfo) {
      uni.request({
        url: config.app_url + "/api/front/index/update",
        data: {
          version: widgetInfo.version,
          appId: config.appId,
          platform: uni.getSystemInfoSync().platform,
        },
        success: (result) => {
          var data = result.data.data.result;
          if (data.update && data.wgtUrl) {
            self.updateWgt(data.wgtUrl);
          }
          if (data.update && data.pkgUrl) {
            plus.nativeUI.confirm(
              self.$t('common.has_last_version'),
              function (e) {
                if (e.index == 0) {
                  plus.runtime.openURL(data.pkgUrl);
                }
              },
              {
                title: self.$t('common.update_tip'),
                buttons: [self.$t('common.confirm'),self.$t('common.cancel') ],
                verticalAlign: "center",
              }
            );
          }
        },
        error: (error) => {
          console.log("----------------error");
          console.log(error);
        },
      });
    });
    // #endif
    //应用启动参数
    this.onStartupScene(e.query);
    this.getNav();
  },
  beforeCreate() {},
  onShow: function () {
    //console.log('App Show')
    //#ifdef APP-PLUS
    getApp().globalData.vueObj = this;
    //#endif
  },
  onHide: function () {
    //console.log('App Hide')
  },
  methods: {
    // mpState 1 开启公总号微信授权 0不开启公总号微信授权
    getWxopen() {
      let self = this;
      uni.request({
        url: this.config.app_url + "/api/front/index/loginSetting",
        data: {
          appId: this.config.appId,
        },
        success: (result) => {
          console.log(result.data);
          uni.setStorageSync("mpState", result.data.data.mpState);
          uni.setStorageSync("wxOpen", result.data.data.wxOpen);
          uni.setStorageSync("wxBinding", result.data.data.wxBinding);
          uni.setStorageSync("wxPhone", result.data.data.wxPhone);
          uni.setStorageSync("smsOpen", result.data.data.h5SmsOpen);
        },
      });
    },
    isFirstEnter() {
      var firstEnter = uni.getStorageSync("firstEnter"); //同步获取缓存中是否有首次进入字段
      let self = this;
      uni.getSystemInfo({
        success(data) {
          console.log("firstEnter=" + firstEnter);
          // 如果是ios并且没有firstEnter缓存则弹出模态框
          if (data.platform == "ios" && !firstEnter) {
            console.log("---------------");
            uni.navigateTo({
              url: "/pages/privacy/privacy",
            });
          }
        },
      });
    },
    updateManager: function () {
      const updateManager = uni.getUpdateManager();
      const self=this;
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function (res2) {
            uni.showModal({
              title:self.$t('common.update_tip'),
              content:self.$t('common.update_reload'),
              showCancel: false,
              success(res2) {
                if (res2.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              },
            });
          });
        }
      });

      updateManager.onUpdateFailed(function (res) {
        // 新的版本下载失败
        uni.showModal({
          title: self.$t('common.update_tip'),
          content:self.$t('common.update_load_error'),
          showCancel: false,
        });
      });
    },
    /**
     * 小程序启动场景
     */
    onStartupScene(query) {
      // 获取场景值
      let scene = utils.getSceneData(query);
      // 记录推荐人id
      let refereeId = query.refereeId;
      if (refereeId > 0) {
        if (!uni.getStorageSync("refereeId")) {
          uni.setStorageSync("refereeId", refereeId);
        }
      }
      // 记录分销人id
      let uid = scene.uid;
      if (uid > 0) {
        uni.setStorageSync("refereeId", uid);
      }
      // 邀请有礼id
      let invitationId = query.invitationId;
      if (invitationId > 0) {
        uni.setStorageSync("invitationId", invitationId);
      }
      let invitid = scene.invitid;
      if (invitid > 0) {
        uni.setStorageSync("invitationId", invitid);
      }
      // 如果是h5，设置appId
      // #ifdef  H5
      let appId = query.appId;
      if (appId > 0) {
        uni.setStorageSync("appId", appId);
      }
      if (uni.getStorageSync("appId")) {
        this.config.appId = uni.getStorageSync("appId");
      }
      // #endif
    },
    getNav() {
      this.getWxopen();
      // 如果是android不处理图标,不起作用
      uni.request({
        url: this.config.app_url + "/api/front/index/nav",
        data: {
          appId: this.config.appId,
        },
        success: (result) => {
          let vars = result.data.data.nav;
          let theme = result.data.data.theme.theme;
          this.$store.commit("changeTheme", theme);
          uni.setStorageSync("theme", theme);
          uni.setStorageSync("TabBar", vars);
          uni.setStorageSync("tabInited", vars.isAuto);
          this.setTabBarLinks(vars, theme);
        },
      });
    },
    updateWgt(wgtUrl) {
    let self =this;
      uni.showModal({
        title: self.$t('common.update'),
        content:self.$t('common.update_please_click'),
        confirmText:self.$t('common.update_but'),
        showCancel: false,
        success: function (e) {
          if (e.confirm) {
            var dtask = plus.downloader.createDownload(
              wgtUrl,
              {},
              function (d, status) {
                uni.showToast({
                  title: self.$t('common.install_complate'),
                  mask: false,
                  duration: 1000,
                });
                // 下载完成
                if (status == 200) {
                  plus.runtime.install(
                    d.filename,
                    {
                      force: true,
                    },
                    function () {
                      console.log("install success...");
                      plus.nativeUI.alert(
                        self.$t('common.last_version'),
                        function () {
                          plus.runtime.restart();
                        },
                        self.$t('common.update_tip'),
                        self.$t('common.confirm')
                      );
                    },
                    function (e) {
                      console.log(e);
                      console.log(d.filename);
                      uni.showToast({
                        title:self.$t('common.install_error01'),
                        mask: false,
                        duration: 1500,
                      });
                    }
                  );
                } else {
                  uni.showToast({
                    title:self.$t('common.install_error02'),
                    mask: false,
                    duration: 1500,
                  });
                }
              }
            );
            try {
              dtask.start(); // 开启下载的任务
              var prg = 0;
              var showLoading = plus.nativeUI.showWaiting(self.$t('common.ondown')); //创建一个showWaiting对象
              dtask.addEventListener("statechanged", function (task, status) {
                // 给下载任务设置一个监听 并根据状态  做操作
                switch (task.state) {
                  case 1:
                    showLoading.setTitle(self.$t('common.ondown'));
                    break;
                  case 2:
                    showLoading.setTitle(self.$t('common.connect_server'));
                    break;
                  case 3:
                    prg = parseInt(
                      (parseFloat(task.downloadedSize) /
                        parseFloat(task.totalSize)) *
                        100
                    );
                    showLoading.setTitle("  "+self.$t('common.ondown') + prg + "%  ");
                    break;
                  case 4:
                    plus.nativeUI.closeWaiting();
                    //下载完成
                    break;
                }
              });
            } catch (err) {
              plus.nativeUI.closeWaiting();
              uni.showToast({
                title: self.$t('common.install_error03'),
                mask: false,
                duration: 1500,
              });
            }
          } else {
            //取消
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
@import "./common/iconfont.css";
@import "./common/myIcon.css";
/*每个页面公共css */
@import "./common/style.scss";
page {
  background: #f6f6f6;
  font-size: 0.75rem;
  min-height: 100vh;
}
.icon.iconfont {
  font-family: iconfont !important;
}
</style>
